<?php

if(!class_exists("Imagick")) {
	die("Imagick not installed.");
}

$root = getcwd() . DIRECTORY_SEPARATOR;
$base = $root . @$_GET["base"];
$path = $base . @$_GET["path"];

$base = preg_replace('/[\\/\\\\]/', DIRECTORY_SEPARATOR, $base);
$path = preg_replace('/[\\/\\\\]/', DIRECTORY_SEPARATOR, $path);

if($path && !is_dir($path)) {
	
	if(!file_exists($path)) {
		$path = "$base" . DIRECTORY_SEPARATOR . "no-image.png";
	}
	preg_match_all('/([^\/\\\\]+)\.([^\/\\\\]+)$/', $path, $matches);
	$filename = $matches[1][0];
	$ext = $matches[2][0];
	
	$w = (int)@$_GET["w"];
	$h = (int)@$_GET["h"];
	$force = (int)@$_GET["force"];
	
	$img = new Imagick($path);
	if($force && $w && $h) {
		$img->thumbnailImage($w, $h);
	}else{	
		if($w>0) {
			$img->thumbnailImage($w, 0);
		}
		if($h>0) {
			$img->thumbnailImage(0,$h);
		}
		
		$w_original = $img->getImageWidth();
		$h_original = $img->getImageHeight();
		
		if($h>0 && ($h<$h_original || $force)) {
			$w = round($w_original * $h / $h_original);
			$img->thumbnailImage($w, $h);
		}
	}
	
	header("Content-Type: image/$ext");
	header("Content-Disposition:inline; filename=$filename.$ext");
	echo $img;
}else{	
	header("HTTP/1.0 403 Forbidden");
	?>
	<h1>You are not authorized to view this item</h1>
	<p>-- <a href="/">Giftshop@Kliker</a></p>
	<?php
}

?>